package com.ibeacon.service.impl;


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;
import com.ibeacon.controller.common.WeixinUtil;
import com.ibeacon.model.BeaconInfo;
import com.ibeacon.model.BeaconsInfo;
import com.ibeacon.controller.common.Log;
import com.ibeacon.controller.common.TokenThread;
import com.ibeacon.service.IbeaconDeviceService;


@Service("IbeaconDeviceService")
public class IbeaconDeviceServiceImpl implements IbeaconDeviceService {
	Log log = Log.getLogger();
	public  List<BeaconInfo>  queryDevice(){

		String accessToken = TokenThread.accessToken.getToken();
		System.out.println(accessToken);
		
			String url1 = "https://api.weixin.qq.com/shakearound/device/search?access_token="+accessToken;
			JSONObject json = new JSONObject();
			/**
			 * 按页查询
			 */
			json.put("type",2);
			json.put("begin",0);
			json.put("count",50);
			
			/**
			 * 按设备查询
			 */
//			json.put("type",1);
//			JSONObject jsons = new JSONObject();
//			jsons.put("device_id", 810576);
//			jsons.put("uuid", "FDA50693-A4E2-4FB1-AFCF-C6EB07647825");
//			jsons.put("major", 10009);
//			jsons.put("minor", 17555);
//			List<JSONObject> list = new ArrayList<JSONObject>();
//			list.add(jsons);
//			json.put("device_identifiers", list);
			
			String sJson = json.toString();
			JSONObject jo = WeixinUtil.httpRequest(url1, "POST", sJson);
			List<BeaconInfo> retList = new ArrayList<BeaconInfo>();
			try{
				if(jo !=null && !"".equals(jo.get("data"))){
					JSONObject data =  JSONObject.fromObject(jo.get("data"));
					
					List<Object> devices =  (List<Object>) data.get("devices");
					for(Object jodata : devices){
						BeaconInfo beaconInfo = new BeaconInfo();
						if(jodata!=null && !"".equals(((JSONObject) jodata).get("comment"))){
							beaconInfo.setComment(((JSONObject) jodata).get("comment").toString());
						}
						if(jodata!=null && !"".equals(((JSONObject) jodata).get("device_id"))){
							beaconInfo.setDeviceId(((JSONObject) jodata).get("device_id").toString());
						}
						if(jodata!=null && !"".equals(((JSONObject) jodata).get("status"))){
							beaconInfo.setStatus(((JSONObject) jodata).get("status").toString());
						}
						if(jodata!=null && !"".equals(((JSONObject) jodata).get("last_active_time"))){
							beaconInfo.setLastActiveTime(((JSONObject) jodata).get("last_active_time").toString());
						}
						if(jodata!=null && !"".equals(((JSONObject) jodata).get("poi_id"))){
							beaconInfo.setPoiId(((JSONObject) jodata).get("poi_id").toString());
						}
						if(jodata!=null && !"".equals(((JSONObject) jodata).get("major"))){
							beaconInfo.setMajor(((JSONObject) jodata).get("major").toString());
						}
						if(jodata!=null && !"".equals(((JSONObject) jodata).get("minor"))){
							beaconInfo.setMinor(((JSONObject) jodata).get("minor").toString());
						}
						if(jodata!=null && !"".equals(((JSONObject) jodata).get("uuid"))){
							beaconInfo.setUuid(((JSONObject) jodata).get("uuid").toString());
						}
						retList.add(beaconInfo);
					}
				}
			}catch(Exception e){
				log.logger.error("查询设备失败");
				e.getStackTrace();
			}
		
		
		return retList;
	
	}
	
	
	public List<BeaconInfo> getIbeaconDevice(HashMap<String, Object> paraMap){
		String accessToken = TokenThread.accessToken.getToken();
		System.out.println(accessToken);
		String ticket = "";
		BeaconInfo beaconInfo = new BeaconInfo();
		if(paraMap.get("ticket")!=null && !"".equals(paraMap.get("ticket"))){
			ticket = paraMap.get("ticket").toString();
		}
		if(ticket != null && !"".equals(ticket)){
			log.logger.info("获取ticket成功："+ticket);
			String url1 = "https://api.weixin.qq.com/shakearound/user/getshakeinfo?access_token="+accessToken;
			JSONObject json = new JSONObject();
			json.put("ticket", ticket);
			json.put("need_poi",1);
			String sJson = json.toString();
			JSONObject jo = WeixinUtil.httpRequest(url1, "POST", sJson);
			
			try{
				if(jo !=null && !"".equals(jo.get("data"))){
					JSONObject jodata =  JSONObject.fromObject(jo.get("data"));
					if(jodata!=null && !"".equals(jodata.get("page_id"))){
						beaconInfo.setPageId(jodata.get("page_id").toString());
					}
					if(jodata!=null && !"".equals(jodata.get("openid"))){
						beaconInfo.setOpenId(jodata.get("openid").toString());
					}
					if(jodata!=null && !"".equals(jodata.get("poi_id"))){
						beaconInfo.setPoiId(jodata.get("poi_id").toString());
					}
					JSONObject beacon_info  =JSONObject.fromObject(jodata.get("beacon_info"));
					if(beacon_info!=null && !"".equals(beacon_info.get("distance"))){
						beaconInfo.setDistance(beacon_info.get("distance").toString());
					}
					if(beacon_info!=null && !"".equals(beacon_info.get("major"))){
						beaconInfo.setMajor(beacon_info.get("major").toString());
					}
					if(beacon_info!=null && !"".equals(beacon_info.get("minor"))){
						beaconInfo.setMinor(beacon_info.get("minor").toString());
					}
					if(beacon_info!=null && !"".equals(beacon_info.get("uuid"))){
						beaconInfo.setUuid(beacon_info.get("uuid").toString());
					}
				}
			}catch(Exception e){
				log.logger.error("查询设备失败");
				e.getStackTrace();
			}
		}else{
			log.logger.info("查询ibeacon设备的ticket获取失败：");
		 }
		List<BeaconInfo> retList = new ArrayList<BeaconInfo>();
		retList.add(beaconInfo);
		return retList;
	}
	
	
	@SuppressWarnings("unchecked")
	public  BeaconsInfo getIbeaconDevices(String xmlsb){
		/**
		 * 数据包格式
		 <xml>
			<ToUserName><![CDATA[toUser]]></ToUserName>
			<FromUserName><![CDATA[fromUser]]></FromUserName>
			<CreateTime>1433332012</CreateTime>
			    <MsgType><![CDATA[event]]></MsgType>
			    <Event><![CDATA[ShakearoundUserShake]]></Event>
			    <ChosenBeacon>
			        <Uuid><![CDATA[uuid]]></Uuid>
			        <Major>major</Major>
			        <Minor>minor</Minor>
			        <Distance>0.057</Distance>
			    </ChosenBeacon>
			    <AroundBeacons>
			        <AroundBeacon>
			            <Uuid><![CDATA[uuid]]></Uuid>
			            <Major>major</Major>
			            <Minor>minor</Minor>
			            <Distance>166.816</Distance>
			        </AroundBeacon>
			        <AroundBeacon>
			            <Uuid><![CDATA[uuid]]></Uuid>
			            <Major>major</Major>
			            <Minor>minor</Minor>
			            <Distance>15.013</Distance>
			        </AroundBeacon>
			    </AroundBeacons>
			</xml>
		 */
		String xml = xmlsb;
		BeaconsInfo beaconsInfo = new BeaconsInfo();
		log.logger.info("开始解析xml数据包");
		try {
			Document document = DocumentHelper.parseText(xml);
			Element root = document.getRootElement();
			//开发者微信号
			Element toUserName_element = root.element("ToUserName");
			beaconsInfo.setToUserName(toUserName_element.getText());
			//摇一摇用户（一个OpenID）
			Element fromUserName_element = root.element("FromUserName");
			beaconsInfo.setFromUserName(fromUserName_element.getText());
			//消息创建时间 （整型）
			Element createTime_element = root.element("CreateTime");
			beaconsInfo.setCreateTime(createTime_element.getText());
			//消息类型，event
			Element msgType_element = root.element("MsgType");
			beaconsInfo.setMsgType(msgType_element.getText());
			
			List<BeaconInfo> beacons = new ArrayList<BeaconInfo>();
			BeaconInfo chosenbeaconInfo = new BeaconInfo();
			//选中的ibeacon
			Element chosenBeacon_element = root.element("ChosenBeacon");
			chosenbeaconInfo.setUuid(chosenBeacon_element.element("Uuid").getText());
			chosenbeaconInfo.setMajor(chosenBeacon_element.element("Major").getText());
			chosenbeaconInfo.setMinor(chosenBeacon_element.element("Minor").getText());
			chosenbeaconInfo.setDistance(chosenBeacon_element.element("Distance").getText());
			beacons.add(chosenbeaconInfo);
			//周围的ibeacon
			Element  aroundBeacons_element = root.element("AroundBeacons");
			List<Element> aroundBeacons = aroundBeacons_element.elements();
			for(Element aroundBeacon : aroundBeacons){
				BeaconInfo aroundbeaconInfo = new BeaconInfo();
				aroundbeaconInfo.setUuid(aroundBeacon.element("Uuid").getText());
				aroundbeaconInfo.setMajor(aroundBeacon.element("Major").getText());
				aroundbeaconInfo.setMinor(aroundBeacon.element("Minor").getText());
				aroundbeaconInfo.setDistance(aroundBeacon.element("Distance").getText());
				beacons.add(aroundbeaconInfo);
			}
			beaconsInfo.setBeaconInfo(beacons);
		} catch (DocumentException e1) {
			log.logger.info("解析xml数据包失败");
			e1.printStackTrace();
		}  
			log.logger.info("解析xml数据包完成");
			return beaconsInfo;
	}
	
	public JSONObject addIbeaconGroup(String groupName){
		String accessToken = TokenThread.accessToken.getToken();
		JSONObject jo = new JSONObject();
		if(groupName != null && !"".equals(groupName)){
			log.logger.info("groupName："+groupName);
			String url1 = "https://api.weixin.qq.com/shakearound/device/group/add?access_token="+accessToken;
			JSONObject json = new JSONObject();
			json.put("group_name", groupName);
			String sJson = json.toString();
			jo = WeixinUtil.httpRequest(url1, "POST", sJson);
		}
		return jo;
	}
	
	public JSONObject queryIbeaconGroup(){
		String accessToken = TokenThread.accessToken.getToken();
		JSONObject jo = new JSONObject();
		String url1 = "https://api.weixin.qq.com/shakearound/device/group/getlist?access_token="+accessToken;
		JSONObject json = new JSONObject();
		json.put("begin", 0);
		json.put("count", 100);
		String sJson = json.toString();
		jo = WeixinUtil.httpRequest(url1, "POST", sJson);
		return jo;
	}
	
	public JSONObject deleteIbeaconGroup(String groupId){

		String accessToken = TokenThread.accessToken.getToken();
		JSONObject jo = new JSONObject();
		if(groupId != null && !"".equals(groupId)){
			log.logger.info("groupId："+groupId);
			String url1 = "https://api.weixin.qq.com/shakearound/device/group/delete?access_token="+accessToken;
			JSONObject json = new JSONObject();
			json.put("group_id", Integer.parseInt(groupId));
			String sJson = json.toString();
			jo = WeixinUtil.httpRequest(url1, "POST", sJson);
		}
		return jo;
	}
	
	public String deleteIbeaconGroups(String groupIds){
		 String[] groupIdstr= groupIds.split(",");
		 String accessToken = TokenThread.accessToken.getToken();
			String retMessage = "";
		 for(String groupId:groupIdstr){
			 JSONObject jo = new JSONObject();
			 if(groupId != null && !"".equals(groupId)){
					log.logger.info("groupId："+groupId);
					String url1 = "https://api.weixin.qq.com/shakearound/device/group/delete?access_token="+accessToken;
					JSONObject json = new JSONObject();
					json.put("group_id", Integer.parseInt(groupId));
					String sJson = json.toString();
					jo = WeixinUtil.httpRequest(url1, "POST", sJson);
				}
			 String errmsg =(String) jo.get("errmsg");
			 if(!"success.".equals(errmsg)){
				 retMessage = retMessage + groupId;
			 }
		 }
		 
		
		
		
		return retMessage;
	}
	
	public JSONObject editGroupDetil(String groupId,String groupName){

		String accessToken = TokenThread.accessToken.getToken();
		JSONObject jo = new JSONObject();
		if(groupId != null && !"".equals(groupId)){
			log.logger.info("groupId："+groupId);
			String url1 = "https://api.weixin.qq.com/shakearound/device/group/update?access_token="+accessToken;
			JSONObject json = new JSONObject();
			json.put("group_id", Integer.parseInt(groupId));
			json.put("group_name", groupName);
			String sJson = json.toString();
			jo = WeixinUtil.httpRequest(url1, "POST", sJson);
		}
		return jo;
	}
	
	public JSONObject queryGroupDetil(String groupId){

		String accessToken = TokenThread.accessToken.getToken();
		JSONObject jo = new JSONObject();
		if(groupId != null && !"".equals(groupId)){
			log.logger.info("groupId："+groupId);
			String url1 = "https://api.weixin.qq.com/shakearound/device/group/getdetail?access_token="+accessToken;
			JSONObject json = new JSONObject();
			json.put("group_id", Integer.parseInt(groupId));
			json.put("begin", 0);
			json.put("count", 100);
			String sJson = json.toString();
			jo = WeixinUtil.httpRequest(url1, "POST", sJson);
		}
		return jo;
	}
	
	
	public JSONObject addDeviceToGroup(HashMap<String, String>  pramMap ){

		String accessToken = TokenThread.accessToken.getToken();
		JSONObject jo = new JSONObject();
		
		JSONObject device_identifier = new JSONObject();
		String deviceId =  pramMap.get("deviceId");
		if(deviceId!=null && !"".equals(deviceId)){
			device_identifier.put("device_id", Integer.parseInt(deviceId));
		}
		
		device_identifier.put("uuid", pramMap.get("uuid"));
		String major =  pramMap.get("major");
		if(major!=null && !"".equals(major)){
			device_identifier.put("major", Integer.parseInt(major));
		}
		String minor =  pramMap.get("minor");
		if(minor!=null && !"".equals(minor)){
			device_identifier.put("minor", Integer.parseInt(minor));
		}
		List<JSONObject> device_identifiers = new ArrayList<JSONObject>();
		device_identifiers.add(device_identifier);
		
		String groupId = pramMap.get("groupId");
		if(groupId != null && !"".equals(groupId)){
			log.logger.info("groupId："+groupId);
			String url1 = "https://api.weixin.qq.com/shakearound/device/group/adddevice?access_token="+accessToken;
			JSONObject json = new JSONObject();
			json.put("group_id", Integer.parseInt(groupId));
			json.put("device_identifiers", device_identifiers);
			String sJson = json.toString();
			jo = WeixinUtil.httpRequest(url1, "POST", sJson);
		}
		return jo;
	}
	
	public JSONObject deleteDeviceFromGroup(HashMap<String, String>  pramMap ){

		String accessToken = TokenThread.accessToken.getToken();
		JSONObject jo = new JSONObject();
		
		JSONObject device_identifier = new JSONObject();
		String deviceId =  pramMap.get("deviceId");
		if(deviceId!=null && !"".equals(deviceId)){
			device_identifier.put("device_id", Integer.parseInt(deviceId));
		}
		
		device_identifier.put("uuid", pramMap.get("uuid"));
		String major =  pramMap.get("major");
		if(major!=null && !"".equals(major)){
			device_identifier.put("major", Integer.parseInt(major));
		}
		String minor =  pramMap.get("minor");
		if(minor!=null && !"".equals(minor)){
			device_identifier.put("minor", Integer.parseInt(minor));
		}
		List<JSONObject> device_identifiers = new ArrayList<JSONObject>();
		device_identifiers.add(device_identifier);
		
		String groupId = pramMap.get("groupId");
		if(groupId != null && !"".equals(groupId)){
			log.logger.info("groupId："+groupId);
			String url1 = "https://api.weixin.qq.com/shakearound/device/group/deletedevice?access_token="+accessToken;
			JSONObject json = new JSONObject();
			json.put("group_id", Integer.parseInt(groupId));
			json.put("device_identifiers", device_identifiers);
			String sJson = json.toString();
			jo = WeixinUtil.httpRequest(url1, "POST", sJson);
		}
		return jo;
	}
	
	public Map<String, String> getSign(String jsapi_ticket, String url){
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        return ret;
	}
	private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
	
}
